import 'package:flutter/material.dart';
import './message_data.dart';
import './message_item.dart';
import 'WebViewPage.dart'; // 导入新的 WebViewPage
class MessagePage extends StatefulWidget {
  @override
  MessagePageState createState() => new MessagePageState();
}
class MessagePageState extends State<MessagePage> {
  ScrollController _scrollController = ScrollController();
  List<MessageData> _messageData = List.from(messageData);
  bool _isLoading = false;
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        _loadMoreData();
      }
    });
  }
  Future<void> _refreshData() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      _messageData.insert(
        0,
        MessageData(
          'https://p3.itc.cn/images01/20230308/8b0502ed59bc41119fa93b5795a3b6b3.jpeg',
          '新消息',
          '这是新消息的内容',
          DateTime.now(),
          MessageType.CHAT,
        ),
      );
    });
  }
  void _loadMoreData() async {
    if (_isLoading) return;
    setState(() {
      _isLoading = true;
    });
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      _messageData.addAll(List.generate(
        10,
            (index) => MessageData(
          'https://img2.baidu.com/it/u=1467995838,1393431649&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=749',
          '更多消息 $index',
          '这是更多消息的内容 $index',
          DateTime.now(),
          MessageType.CHAT,
        ),
      ));
      _isLoading = false;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _refreshData,
        child: ListView.builder(
          controller: _scrollController,
          itemCount: _messageData.length + 1,
          itemBuilder: (BuildContext context, int index) {
            if (index == _messageData.length) {
              return _buildLoadingIndicator();
            } else {
              return GestureDetector(
                onTap: () {
                  print('Navigating to WebViewPage');
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => WebViewPage(
                        url: 'https://www.baidu.com',
                      ),
                    ),
                  );
                },
                child: MessageItem(_messageData[index]),
              );
            }
          },
        ),
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Center(
        child: _isLoading ? CircularProgressIndicator() : Container(),
      ),
    );
  }
  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}